<?php

namespace App\Models\Wechat;

use Illuminate\Database\Eloquent\Model;

use DB;
use Cache;

class Mpnews extends Model
{
    protected $table = 'wechat_mpnews';

    //缓存过期时间
    protected $cacheTime = 86400*7;

    /**
     * 根据ID获取缓存图文消息
     * @param  [type] $id [description]
     * @return [type]     [description]
     */
    function cacheFind($id){
        $mpnews = Cache::get(config('app.name').':mpnews:'.$id.':news');
        if(!$mpnews){
            $mpnews = $this->find($id);
            if(!$mpnews){
                return false;
            }
            $wechat_news_ids = trim($mpnews->wechat_news_ids,',');
            $news = DB::select("select * from wechat_news where id in ($wechat_news_ids) ORDER BY field(id,$wechat_news_ids)");
            if(!$news){
                return false;
            }

            foreach ($news as $key => $new) {
                $news[$key]->pic = !stripos($new->pic, 'http://') ? env('APP_URL').$new->pic : $new->pic;
            }

            Cache::put(config('app.name').':mpnews:'.$id.':news', $news,$this->cacheTime);
            return $news;
        }
        return $mpnews;
    }

    public function cacheEmpty($id){
        Cache::forget(config('app.name').':mpnews:'.$id.':news');
        return $this;
    }
}
